from django import forms
from django.contrib.auth.models import User
from .models import Contract, ContractFile, ContractReview, Supplier


class ContractForm(forms.ModelForm):
    """合同表单"""
    
    class Meta:
        model = Contract
        fields = [
            'name', 'contract_number', 'contract_type', 'supplier',
            'signed_date', 'effective_date', 'start_date', 'end_date', 'amount',
            'our_company_name', 'our_company_address', 'our_signatory', 'our_signatory_title',
            'their_company_name', 'their_company_address', 'their_signatory', 'their_signatory_title',
            'main_subject', 'delivery_requirements', 'special_terms',
            'description'
        ]
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入合同名称'
            }),
            'contract_number': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入合同编号'
            }),
            'contract_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'supplier': forms.Select(attrs={
                'class': 'form-select'
            }),
            'signed_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }),
            'effective_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }),
            'start_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }),
            'end_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }),
            'amount': forms.NumberInput(attrs={
                'class': 'form-control',
                'step': '0.01',
                'placeholder': '请输入合同金额'
            }),
            'our_company_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入我方公司名称'
            }),
            'our_company_address': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '请输入我方公司地址'
            }),
            'our_signatory': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入我方签约人姓名'
            }),
            'our_signatory_title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入我方签约人职务'
            }),
            'their_company_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入对方公司名称'
            }),
            'their_company_address': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '请输入对方公司地址'
            }),
            'their_signatory': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入对方签约人姓名'
            }),
            'their_signatory_title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入对方签约人职务'
            }),
            'main_subject': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': '请输入主要标的物描述'
            }),
            'delivery_requirements': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': '请输入交付要求'
            }),
            'special_terms': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': '请输入特殊条款'
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '请输入合同描述'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置供应商选择
        self.fields['supplier'].queryset = Supplier.objects.all()
        self.fields['supplier'].empty_label = "请选择供应商"
        
        # 设置必填字段标记
        required_fields = ['name', 'contract_number', 'supplier', 'start_date', 'end_date', 'amount']
        for field_name in required_fields:
            if field_name in self.fields:
                self.fields[field_name].widget.attrs['required'] = True
    
    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get('start_date')
        end_date = cleaned_data.get('end_date')
        signed_date = cleaned_data.get('signed_date')
        effective_date = cleaned_data.get('effective_date')
        
        # 验证日期逻辑
        if start_date and end_date:
            if start_date >= end_date:
                raise forms.ValidationError("结束日期必须晚于开始日期")
        
        if signed_date and effective_date:
            if signed_date > effective_date:
                raise forms.ValidationError("生效日期不能早于签订日期")
        
        if effective_date and start_date:
            if effective_date > start_date:
                raise forms.ValidationError("开始日期不能早于生效日期")
        
        return cleaned_data


class ContractFileForm(forms.ModelForm):
    """合同文件表单"""
    
    class Meta:
        model = ContractFile
        fields = ['file_type', 'file_name', 'file_path', 'description']
        widgets = {
            'file_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'file_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入文件名称'
            }),
            'file_path': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png'
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '请输入文件描述'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['file_name'].required = True
        self.fields['file_path'].required = True
    
    def clean_file_path(self):
        file = self.cleaned_data.get('file_path')
        if file:
            # 检查文件大小 (最大50MB)
            if file.size > 50 * 1024 * 1024:
                raise forms.ValidationError("文件大小不能超过50MB")
            
            # 检查文件类型
            allowed_extensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.jpg', '.jpeg', '.png']
            file_extension = file.name.lower().split('.')[-1]
            if f'.{file_extension}' not in allowed_extensions:
                raise forms.ValidationError("不支持的文件类型")
        
        return file


class ContractReviewForm(forms.ModelForm):
    """合同审核表单"""
    
    class Meta:
        model = ContractReview
        fields = ['review_type', 'review_notes']
        widgets = {
            'review_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'review_notes': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': '请输入审核意见'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['review_notes'].required = True


class ContractSearchForm(forms.Form):
    """合同搜索表单"""
    search = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '搜索合同名称、编号或供应商...'
        })
    )
    
    contract_type = forms.ChoiceField(
        required=False,
        choices=[('', '所有类型')] + Contract.CONTRACT_TYPE_CHOICES,
        widget=forms.Select(attrs={
            'class': 'form-select'
        })
    )
    
    status = forms.ChoiceField(
        required=False,
        choices=[('', '所有状态')] + Contract.CONTRACT_STATUS_CHOICES,
        widget=forms.Select(attrs={
            'class': 'form-select'
        })
    )
    
    supplier = forms.ModelChoiceField(
        required=False,
        queryset=Supplier.objects.all(),
        empty_label="所有供应商",
        widget=forms.Select(attrs={
            'class': 'form-select'
        })
    )
    
    date_from = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'form-control',
            'type': 'date'
        })
    )
    
    date_to = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'form-control',
            'type': 'date'
        })
    )